import 'package:flutter/material.dart';
import 'package:flutter_login/flutter_login.dart';
import 'package:spring_fairy/api/user_api.dart';
import 'package:spring_fairy/api/user_store.dart';
import 'package:spring_fairy/model/config.dart';
import 'package:spring_fairy/model/user.dart';
import '../api/api.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> with SingleTickerProviderStateMixin {
  final UserAPI _userAPI = UserAPI();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FlutterLogin(
        onLogin: _onLogin,
        onRecoverPassword: _onRecoveryPassword,
        onSignup: _onSignup,
      userType: LoginUserType.name,
      validateUserImmediately: false,
      userValidator: (String? name) {
            return null;
      },
      theme: LoginTheme(
        primaryColor: AppConfig.PRIMARY_COLOR,
      ),
      headerWidget: Image.network(AppConfig.LOGIN_BACKGROUND_IMAGE),
    );
  }

  Future<String?> _onLogin(LoginData data) async {
    User? user = await _userAPI.login(data.name, data.password);
    if(user == null) {
      return "Login Failed!";
    }
    UserStore.user = user;
    UserStore.token = API.token;
    UserStore.onLoginStateChange?.call();
    return null;
  }

  Future<String?> _onSignup(SignupData data) async {
    if(data.name == null || data.password == null) {
      return "data error";
    }
    User? user = await _userAPI.register(data.name!, data.password!, '');
    if(user == null) {
      return "Register Error!";
    } else {
      UserStore.user = user;
      UserStore.token = API.token;
      UserStore.onLoginStateChange?.call();
      return null;
    }
  }

  Future<String?> _onRecoveryPassword(String username) {
    throw "UnImplement";
  }
}
